from yaps import Plugin


class help(Plugin):
  def __init__(self,parent):
    Plugin.__init__(self,parent)
    self.parent.mbbs.registerFunction(self.help)
    
  def help(self,param1="",param2=""):
    """\n\thelp [commandname]\n\n\tDisplays the help documentation to a command.\n\tIf no commandname is given it displays the list of commands available.\n"""

    if param1=="":
      cmdlist = ""
      for i in self.parent.mbbs.listFunctions():
        cmdlist += "%s " % i
        ret = "Available commands: %s" % cmdlist
    else:
      param1 = param1.strip()
      try:
        exec("mdoc = self.parent.mbbs.%s.__doc__" % param1)
        ret = mdoc
      except:
        ret = "command '%s' not found in the help." % param1
      
    return(ret)

class variables(Plugin):
  def __init__(self,parent):
    Plugin.__init__(self,parent)
    self.parent.mbbs.registerFunction(self.setvar)
    self.parent.mbbs.registerFunction(self.getvar)
    self.parent.mbbs.registerFunction(self.showvars)
    self.parent.mbbs.registerFunction(self.replacevars)
    self.variables = {}
    import os
    self.os = os
    
  def setvar(self,param1="",param2=""):
    """\n\tsetvar <variablename> <value>\n\n\tSets an environment variable with the given value.\n"""
    
    cmd, param = self.parent.divideCmdString(param1)
    if cmd!="":
        self.os.environ[cmd]=param
        
    return("")
    
  def getvar(self,param1="",param2=""):
    """\n\tgetvar <variablename>\n\n\tReturns the value of an environment variable.\n"""
    cmd, param = self.parent.divideCmdString(param1)
    ret = ""
    if cmd!="":
        ret = self.os.environ[cmd]
    return(ret)
  
  def showvars(self, param1="", param2=""):
    """\n\tshowvars \n\n\tReturns the values of all environment variables.\n"""
    m = {}
    for i in self.os.environ.keys():
        m[i]=self.os.environ[i]
    return(m)
    
  def replacevars(self, mstr="", param2=""):
      """\n\treplacevars <string>\n\n\tReturns the string with all occurances of all environment variables replaced by its value.\n"""
      import re
      regexp = re.compile(r"""(%{)([^}]*)(})""")
      res = regexp.findall(mstr)
      for i in res:
          try:
              replstr = self.os.environ[i[1]]
          except:
              replstr = ""
          
          srchstr = "%%{%s}" % i[1]
          mstr = mstr.replace(srchstr, replstr)
      
      return(mstr)
